package io.bitmax.library.mvp;


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by gongdongyang on 2018/9/17.
 */

public abstract class LazyloadFragment extends Fragment {
    private boolean isViewCreated;
    private boolean isUIVisible;

    @Nullable
    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //super.onCreateView(inflater, container, savedInstanceState);
        if (getLayoutId() != 0) {
            return inflater.inflate(getLayoutId(), container, false);
        }else{
            return super.onCreateView(inflater, container, savedInstanceState);
        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        // 执行懒加载,因为无法确定setUserVisibleHint和onViewCreated哪个方法先执行，因此两个方法里面都需要调用lazyLoad
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isUIVisible = true;
            lazyLoad();
        }else{
            isUIVisible = false;
        }
    }


    protected abstract int getLayoutId();

    private void lazyLoad() {
        //需要进行双重判断，避免因为setUserVisibleHint先于onViewCreaetd调用时，出现空指针
        if (isViewCreated && isUIVisible) {
            initViewsAndEvents();
            //onFirstUserVisible();  //进行初次可见时的加载
            //数据加载完毕,恢复标记,防止重复加载
            isViewCreated = false;
            isUIVisible = false;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //页面销毁,恢复标记
        isViewCreated = false;
        isUIVisible = false;
    }


    protected abstract void initViewsAndEvents();

    /*protected abstract void onFirstUserVisible();

    protected abstract void onUserVisible();

    protected abstract void onFirstUserInvisible();

    protected abstract void onUserInvisible();*/
}
